package com.rjj.wlqq.wx.tool;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.rjj.wlqq.wx.common.constant.HttpUrl;
import com.rjj.wlqq.wx.common.core.ApiConfig;
import com.rjj.wlqq.wx.common.core.ApiConfigKit;
import com.rjj.wlqq.wx.entity.token.ErrorMsg;
import com.rjj.wlqq.wx.entity.token.AccessToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author r
 * @date 2020/12/26 20:54
 * 微信工具
 */
@Slf4j
@Component
public class WxKit
{
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取token
     */
    public String getAccessToken(){
        final String accessToken = redisUtil.get(ApiConfigKit.getAppId());
        if(null != accessToken){
            return accessToken;
        }
        final ApiConfig apiConfig = ApiConfigKit.getApiConfig();
        final String response = HttpRequest.post(HttpUrl.getTokenUrl(apiConfig.getAppId(), apiConfig.getAppSecret()))
                .execute().body();

        if(StringUtils.isNotBlank(response) && response.contains("access_token") && response.contains("expires_in")){
            final AccessToken token = JSON.parseObject(response, AccessToken.class);
            redisUtil.set(ApiConfigKit.getAppId(),token.getAccess_token(),token.getExpires_in() - 200);
            return token.getAccess_token();
        }
        final ErrorMsg errorMsg = JSON.parseObject(response, ErrorMsg.class);
        log.warn("获取token失败：【errcode：{}，errmsg：{}】",errorMsg.getErrcode(),errorMsg.getErrmsg());
        return null;
    }
}
